const WebSocket = require('ws');

const wss = new WebSocket.Server({
  port: 4399,
});

wss.on('connection', ws => {

  // 广播进入房间
  console.log('[Server] Connected');
  ws.send(encode({
    id: 'Administrator',
    data: { name: 'Administrator', content: '新人进入了房间' }
  }));

  // 直接转发所有消息
  ws.on('message', message => {
    console.log('[Server] Received message', message);
    wss.clients.forEach(client => {
      client.send(message, handleError);
    });
  });

  // 处理错误
  ws.on('error', handleError);

});

function encode(message) {
  return JSON.stringify(message);
}

function decode(message) {
  return JSON.parse(message);
}

function handleError(err) {
  if (err) {
    console.error(err);
  }
}
